/* eslint-disable eqeqeq */
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { connect } from 'dva';
import { ModalC, PrimaryGhostC, NestedTableC, FundApplicationIndustryC, SelectC } from '@/src/comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import config from '../../../../comps/business/tradingMarket/config';
import myStyle from '../index.less';
import { findValueByCode, formSelectData, getColumnIntoWidth } from '@/src/utils/utils';
import uuid from 'es6-uuid';
import { message } from 'antd';

const myModal = ({
  visible,
  changeVisible,
  bondTypeList,
  loading,
  dispatch,
  form,
  holdDate,
  globalM: {
    // eslint-disable-next-line camelcase
    dataDictionary: { Bond_Type_PBC = [], GJTJJHYFLI = [], SUPPLEMENTARY_TOOL_DICT = [], ISSUER_BY_SIZE = [], ORIGIN_TYPE_DICT = [] },
  },
}) => {
  const [isModalOpen, setIsModalOpen] = useState(visible); // 弹窗与否
  const [dataSource, setDataSource] = useState([]); // 列表data
  const [clickRow, setClickRow] = useState(undefined); // 正在点击的行数据
  const [expandedKeys, setExpandedKeys] = useState(undefined); // 展开的key
  const [oldRow, setOldRow] = useState(undefined); // 存放当前编辑的行旧值
  const [saveData, setSaveData] = useState(undefined); // 存放保存后的行的相关数据

  const columnsChild = [
    { title: '证券代码', key: 'tradingCode' },
    { title: '证券名称', key: 'secuabbr' },
    {
      title: '发行机构所属行业',
      key: 'issuerIndustry',
      width: 220,
      render: (text, record) => {
        if (record.isEdit) {
          return (
            <FundApplicationIndustryC
              form={form}
              dataIndex='issuerIndustry'
              title=''
              initialValue={text}
              OnlySupportFirstLevel={true}
              parentCanClick={true}
              positionBody={true}
              rules={[{ required: true, message: '请选择' }]}
            />
          );
        }
        return findValueByCode(text, GJTJJHYFLI);
      },
    },
    {
      title: '发行机构类型(按规模划分)',
      key: 'issuerScale',
      width: 220,
      render: (text, record) => {
        if (record.isEdit) {
          return (
            <SelectC
              form={form}
              dataIndex='issuerScale'
              title=''
              initialValue={text}
              positionBody={true}
              dataSource={formSelectData(ISSUER_BY_SIZE)}
              rules={[{ required: true, message: '请选择' }]}
            />
          );
        }
        return findValueByCode(text, ISSUER_BY_SIZE);
      },
    },
    {
      title: '交易市场',
      key: 'securityExchange',
      render: (text, record) => {
        let temp = '--';
        config.map((item) => {
          if (item.value == text) {
            temp = item.title;
          }
        });
        return temp;
      },
    },
    {
      title: '类型',
      key: 'bondType',
      render: (text, record) => {
        let temp = '--';
        if (text === '理财直融') {
          return text;
        }
        bondTypeList.map((item) => {
          if (item.value == text) {
            temp = item.title;
          } else if (item.children && item.children.length) {
            item.children.map((childItem) => {
              if (childItem.value == text) {
                temp = childItem.title;
              }
            });
          }
        });
        return temp;
      },
    },
    {
      title: '债券评级',
      key: 'bondRating',
      render: (text, record) => {
        if (record.bondType === '理财直融') {
          // 理财直融时 显示空白
          return '';
        }
        if (text == 'NOT_RATED') {
          text = '无评级';
        }
        return text || '--';
      },
    },
    {
      title: '补充工具',
      key: 'supplementaryTool',
      render: (text, record) => {
        if (record.bondType === '理财直融') {
          // 理财直融时 显示空白
          return '';
        }
        return findValueByCode(text, SUPPLEMENTARY_TOOL_DICT);
      },
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      type: 'operate',
      fixed: 'right',
      operates: [
        {
          title: '保存',
          onClick: (record) => {
            saveItem(record);
          },
          rules: {
            // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
            hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
          },
        },
        {
          title: '取消',
          onClick: (record, index) => {
            cancelItem(record);
          },
          rules: {
            // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
            hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
          },
        },
        {
          title: '编辑',
          onClick: (record, index) => {
            editItem(record);
          },
          rules: {
            hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['!='] }] },
          },
        },
      ],
    },
  ];
  const columnsP = [{ title: '发行人', key: 'issuer', align: 'left' }];

  useEffect(() => {
    getVerifyData(); // 获取列表
  }, []); // 仅首次加载的时候进入
  const handleOk = () => {
    handleCancel();
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    // 通知父组件关闭弹窗
    changeVisible(false);
  };
  const onRefrish = () => {
    getVerifyData(); // 获取列表
  };
  // 保存数据
  const saveItem = (row) => {
    const { validateFields } = form;
    validateFields((err, values) => {
      if (err) {
        row.key = uuid(16); // 还是为了渲染 页面有红色报错出现
        return;
      }
      // 因该接口保存太慢 页面先恢复
      setSaveData({
        ...values,
        id: row.id,
        pid: row.pid,
      });
      dispatch({
        type: 'manbondInfoM/saveVerifyData',
        payload: {
          ...values,
          id: row.id,
        },
        callback: () => {
          setClickRow(undefined);
          setOldRow(undefined);
        },
      });
    });
  };
  const cancelItem = (row) => {
    const temp = _.cloneDeep(row);
    temp.isEdit = undefined;
    setClickRow({ ...temp });
    setOldRow(undefined); // 删除缓存的编辑行
  };
  const editItem = (row) => {
    // 这里取不到state里的数据，所以只能保存了当前点击行的数据
    const temp = _.cloneDeep(row);
    temp.isEdit = true;
    setClickRow({ ...temp });
    setSaveData(undefined); // 清空
  };
  useEffect(() => {
    console.log('进入编辑,取消', clickRow);
    if (dataSource?.length && clickRow) {
      if (oldRow && clickRow?.id != oldRow.id) {
        // 用当点击行的数据id 与 正在编辑的行的缓存对比
        message.warning('有正在编辑中的数据，请保存后再进行操作！');
        return;
      }
      dataSource.map((item) => {
        if (clickRow.pid === item.id) {
          item.nestedConfig?.dataSource?.map((x) => {
            if (x.id == clickRow.id) {
              x.isEdit = clickRow.isEdit;
              x.key = uuid(16); // 为了子表编辑的时候能够渲染
            }
            return { ...x };
          });
        }
      });
      setDataSource([...dataSource]);
      if (clickRow.isEdit) setOldRow(clickRow); // 缓存正在编辑的行
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [clickRow]); //
  useEffect(() => {
    console.log('进入保存', saveData);
    if (dataSource?.length && saveData) {
      dataSource.map((item) => {
        if (saveData.pid === item.id) {
          item.nestedConfig?.dataSource?.map((x) => {
            if (x.id == saveData.id) {
              x.issuerIndustry = saveData.issuerIndustry;
              x.issuerScale = saveData.issuerScale;
              x.isEdit = saveData.isEdit;
              x.key = uuid(16); // 为了子表保存的时候能够渲染
            }
            return { ...x };
          });
        }
      });
      setDataSource([...dataSource]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [saveData]); //
  // 获取同发行人数据
  const getVerifyData = () => {
    setOldRow(undefined); // 删除缓存的数据
    setClickRow(undefined);
    setSaveData(undefined); // 清空
    dispatch({
      type: 'manbondInfoM/getVerifyData',
      payload: {
        holdDate,
      },
      callback: (data) => {
        if (data?.length) {
          data.map((item) => {
            item.nestedConfig = {
              rowKey: 'key',
              columns: columnsChild,
              dataSource: item.childData.map((item) => {
                item.key = uuid(16);
                return item;
              }),
              hidePage: true,
            };
            delete item.childData;
          });
          setDataSource([...data]);
          const keys = [data[0].id];
          setExpandedKeys([...keys]);
        } else {
          setDataSource([]);
        }
      },
    });
  };
  // 表格展开关闭
  const onExpand = (expanded, record) => {
    let newArr = null;
    if (!expanded) {
      newArr = expandedKeys.filter((item) => item != record.id);
      setExpandedKeys([...newArr]);
    } else {
      expandedKeys.push(record.id);
      setExpandedKeys([...expandedKeys]);
    }
  };

  return (
    <div>
      <ModalC title={'同发行人校验'} visible={isModalOpen} maskClosable={false} onOk={handleOk} onCancel={handleCancel} width={1600} footer={null}>
        <div className={myStyle.modalCls}>
          <PrimaryGhostC title='刷新' onClick={onRefrish} style={{ marginBottom: '15px' }} />
          <NestedTableC
            columns={columnsP}
            dataSource={dataSource}
            expandedRowKeys={expandedKeys}
            onExpand={onExpand}
            loading={loading}
            scroll={{ y: 500 }}
            hidePage={true}
            rowKey='id'
          />
        </div>
      </ModalC>
    </div>
  );
};
const mapState = ({ manbondInfoM, globalM, loading }) => ({ manbondInfoM, globalM, loading: loading.effects['manbondInfoM/getVerifyData'] });
export default connect(mapState)(Form.create()(myModal));
